﻿using SpreadsheetGear;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.ComprehensiveESGResearch.Service.Features
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("ComprehensiveESGResearch")]
    public class ComprehensiveESGResearchExportController : ApiController
    {
        private readonly ComprehensiveESGResearchHandler comprehensiveESGResearchHandler;

        public ComprehensiveESGResearchExportController(
            ComprehensiveESGResearchHandler comprehensiveESGResearchHandler)
        {
            this.comprehensiveESGResearchHandler = comprehensiveESGResearchHandler;
        }

        [Route("")]
        [HttpGet]
        public async Task<HttpResponseMessage> GetReport()
        {
            MemoryStream excelStream = new MemoryStream();
            try
            {


                IWorkbook workbook = await comprehensiveESGResearchHandler.GenerateReport().ConfigureAwait(false);

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

                workbook.SaveToStream(excelStream, SpreadsheetGear.FileFormat.OpenXMLWorkbook);
                excelStream.Seek(0, SeekOrigin.Begin);
                result.Content = new StreamContent(excelStream);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"Comprehensive_ESG_Research_{DateTime.Now}.xlsx"
                };

                workbook.Close();


                return result;
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }
    }
}
